package com.sgy.handwrite_mvc.mvcframework.servlet;

import com.sgy.handwrite_mvc.mvcframework.annotations.SgyAutowired;
import com.sgy.handwrite_mvc.mvcframework.annotations.SgyController;
import com.sgy.handwrite_mvc.mvcframework.annotations.SgyRequestMapping;
import com.sgy.handwrite_mvc.mvcframework.annotations.SgyService;
import com.sgy.handwrite_mvc.mvcframework.pojo.Handler;
import com.sgy.handwrite_mvc.mvcframework.utils.StringUtils;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SgyDispatcherServlet extends HttpServlet {

    private Properties properties =  new Properties();

    // 缓存扫描到的类的全限定类名
    private List<String> classNames = new ArrayList<>();

    // ioc容器
    private Map<String, Object> ioc = new HashMap<>();

//    private Map<String, Method> handlerMapping = new HashMap<>();

    private List<Handler> handlerMapping = new ArrayList<>();

    /**
     * 重写初始化方法
     * @param config
     * @throws ServletException
     */
    @Override
    public void init(ServletConfig config) throws ServletException {
        // 加载配置文件
        String contextConfigLocation = config.getInitParameter("contextConfigLocation");
        doLoadConfig(contextConfigLocation);
        // 扫描相关类，扫描注解
        doScan(properties.getProperty("scanPackage"));
        // 初始化bean对象（基于注解实现ioc容器）
        doInstance();
        // 实现依赖注入
        doAutowired();
        // 构造一个HandlerMapping处理器映射器，将配置好的url和method建立映射关系
        initHandlerMapping();
        System.out.println("sgy mvc 初始化完成......");

        // 等待请求处理请求
    }

    /**
     * 构造处理器映射器
     */
    private void initHandlerMapping() {
        if (ioc.isEmpty()) return;

        ioc.forEach((s, o) -> {
            // 获取ioc中当前遍历对象的class类型
            Class<?> aClass = o.getClass();
            if (aClass.isAnnotationPresent(SgyController.class)) {
                String baseUrl;
                if (aClass.isAnnotationPresent(SgyRequestMapping.class)) {
                    baseUrl = aClass.getAnnotation(SgyRequestMapping.class).value();
                } else {
                    baseUrl = "";
                }

                // 获取方法
                Method[] methods = aClass.getMethods();
                // 过滤掉没有标注@SgyRequestMapping的方法，并处理标识了@SgyRequestMapping的方法
                Arrays.stream(methods).filter(m -> m.isAnnotationPresent(SgyRequestMapping.class)).forEach(m -> {
                    String methodUrl = m.getAnnotation(SgyRequestMapping.class).value();
                    String url = baseUrl + methodUrl;

                    // 把method所有信息及url封装为一个Handler
                    Handler handler = new Handler(o, m, Pattern.compile(url));

                    // 计算方法的参数位置信息
                    Parameter[] parameters = m.getParameters();
                    for (int i = 0; i < parameters.length; i++) {
                        Parameter parameter = parameters[i];
                        if (parameter.getType() == HttpServletRequest.class || parameter.getType() == HttpServletResponse.class) {
                            // 如果是request和response对象，那么参数名称写HttpServletRequest、HttpServletResponse
                            handler.getParamIndexMapping().put(parameter.getType().getSimpleName(), i);
                        } else {
                            handler.getParamIndexMapping().put(parameter.getName(), i);
                        }
                    }

                    // 建立url和method之间的映射关系
                    handlerMapping.add(handler);
                });
            }
        });
    }

    /**
     * 实现依赖注入
     */
    private void doAutowired() {
        if (ioc.isEmpty()) return;

        // 遍历ioc中的所有对象，查看对象中的字段，是否有@SgyAutowired注解，有对象进行依赖注入
        ioc.forEach((s,o)->{
            // 获取bean对象中的字段信息
            Field[] declaredFields = o.getClass().getDeclaredFields();
            for (Field declaredField : declaredFields) {
                if (!declaredField.isAnnotationPresent(SgyAutowired.class)) {
                    continue;
                }

                // 有@SgyAutowired注解
                SgyAutowired annotation = declaredField.getAnnotation(SgyAutowired.class);
                // 获取需要注入的bean的id
                String beanName = annotation.value();
                if ("".equals(beanName.trim())) {
                    // 没有配置具体的bean id，就需要根据当前字段的类型注入
                    beanName = declaredField.getType().getName();
                }

                // 开启赋值
                declaredField.setAccessible(true);
                try {
                    declaredField.set(o, ioc.get(beanName));
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
            }
        });
    }

    /**
     * ioc容器
     * 基于classNames缓存的类的全限定类名，以及反射技术，完成对象的创建和管理
     */
    private void doInstance() {
        if (classNames.size() == 0) {
            return;
        }
        classNames.forEach(className -> {
            try {
                Class<?> aClass = Class.forName(className);

                // 区分controller、service
                if (aClass.isAnnotationPresent(SgyController.class)) {
                    String simpleName = aClass.getSimpleName(); // DemoController
                    String lowerFirstSimpleName = lowerFirst(simpleName); // demoController
                    Object o = aClass.newInstance();
                    ioc.put(lowerFirstSimpleName, o);
                } else if (aClass.isAnnotationPresent(SgyService.class)) {
                    SgyService annotation = aClass.getAnnotation(SgyService.class);
                    // 获取注解value的值
                    String beanName = annotation.value();
                    // 如果指定了id，就以指定的为准
                    if (!"".equals(beanName.trim())) {
                        ioc.put(beanName, aClass.newInstance());
                    } else {
                        // 如果没有指定，就以类名首字母小写
                        beanName = lowerFirst(aClass.getSimpleName());
                        ioc.put(beanName, aClass.newInstance());
                    }

                    // service层往往有接口，面向接口开发，此时再以接口名为id，放入一份对象到ioc中，便于后期根据接口类型注入
                    Class<?>[] interfaces = aClass.getInterfaces();
                    for (Class<?> anInterface : interfaces) {
                        // 以接口的全限定类名作为id放入
                        ioc.put(anInterface.getName(), aClass.newInstance());
                    }
                }
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            } catch (InstantiationException e) {
                throw new RuntimeException(e);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        });
    }

    /**
     * 首字母小写
     * @param str
     * @return
     */
    private String lowerFirst(String str) {
        char[] charArray = str.toCharArray();
        if (charArray[0] >= 'A' && charArray[0] <= 'Z') {
            charArray[0] = (char) (charArray[0] + 32);
        }
        return String.valueOf(charArray);
    }

    /**
     * 扫描类，扫描注解
     * @param scanPackage 包路径
     */
    private void doScan(String scanPackage) {
        // 将包路径替换为磁盘上的文件路径   com.sgy.handwrite_mvc.demo  -->  com/sgy/handwrite_mvc/demo
        String scanPackagePath = Thread.currentThread().getContextClassLoader().getResource("").getPath() + scanPackage.replaceAll("\\.", "/");
        File pack = new File(scanPackagePath);
        File[] files = pack.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                // 递归拼接包路径  com.sgy.handwrite_mvc.demo.controller
                doScan(scanPackage + "." + file.getName());
            } else if (file.getName().endsWith(".class")) {
                String className = scanPackage + "." + file.getName().replaceAll(".class", "");
                classNames.add(className);
            }
        }
    }

    /**
     * 加载配置文件
     * @param contextConfigLocation
     */
    private void doLoadConfig(String contextConfigLocation) {
        InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
        try {
            properties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 处理请求
        Handler handler = getHandler(req);
        if (handler == null) {
            resp.getWriter().write("404 not found");
        }

        // 参数绑定
        // 获取所有参数类型数组，数组长度就是要传入的args数组的长度
        Class<?>[] parameterTypes = handler.getMethod().getParameterTypes();
        // 根据上述数组长度，创建一个新的参数数组，传入反射调用
        Object[] paraValues = new Object[parameterTypes.length];
        // 遍历request中所有参数
        req.getParameterMap().forEach((k,v)->{
            String value = StringUtils.join(v, ",");
            // 如果参数和方法中的参数匹配上了，填充数据
            if (handler.getParamIndexMapping().containsKey(k)) {
                Integer index = handler.getParamIndexMapping().get(k);
                // 前台传过来的参数值填充到对应的位置
                paraValues[index] = value;
            }
        });

        Integer requestIndex = handler.getParamIndexMapping().get(HttpServletRequest.class.getSimpleName());
        paraValues[requestIndex] = req;
        Integer responseIndex = handler.getParamIndexMapping().get(HttpServletResponse.class.getSimpleName());
        paraValues[responseIndex] = resp;

        // 最终调用handler的method属性
        try {
            handler.getMethod().invoke(handler.getController(), paraValues);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }

    private Handler getHandler(HttpServletRequest req) {
        if (handlerMapping.isEmpty()) return null;
        String requestURI = req.getRequestURI();
        String uri = requestURI.subSequence(req.getContextPath().length(), requestURI.length()).toString();
        for (Handler handler : handlerMapping) {
            Matcher matcher = handler.getPattern().matcher(uri);
            if (!matcher.matches()) {
                continue;
            }
            return  handler;
        }
        return null;
    }
}
